/** 注释
 * @Name globalLoading;
 * @Author FiveXu
 * @Description globalLoading
 * @Date 2021-07-12 14:06
 */

import LoadingVue, { LoadingProps } from '@/base/directive/loading/loading.vue'
import { createApp } from 'vue'
import { getZIndex } from '@/base/hooks'

export interface GlobalLoadingProps extends LoadingProps {
  styles: { [key: string]: string },
  time: number
}

class GlobalLoading {
  props: Partial<GlobalLoadingProps> | undefined
  loadingDom: HTMLElement | undefined
  loadingTimer: ReturnType<typeof setInterval> | undefined

  constructor (props?: Partial<GlobalLoadingProps>) {
    this.props = props
    this.initLoading()
  }

  private static initLoadingStyle (): HTMLElement {
    const dom: HTMLElement = document.createElement('div')
    dom.style.position = 'fixed'
    dom.style.zIndex = String(getZIndex())
    dom.style.left = '0'
    dom.style.top = '0'
    dom.style.right = '0'
    dom.style.bottom = '0'
    return dom
  }

  private initLoading (): void {
    this.close()
    this.loadingDom = GlobalLoading.initLoadingStyle()
    document.body.appendChild(this.loadingDom)
    createApp(LoadingVue, this.props).mount(this.loadingDom)
    if (this.props?.time) {
      if (this.loadingTimer) clearTimeout(this.loadingTimer)
      this.loadingTimer = setTimeout(this.close, this.props.time)
    }
  }

  public close (): void {
    if (this.loadingDom) this.loadingDom.remove()
  }
}

export const Loading = (props?: Partial<GlobalLoadingProps>): GlobalLoading => new GlobalLoading(props)
